package com.haitaoit.chengquan.module.home.activity.maintenance;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.adapter.forum.ForumDownAdapter;
import com.haitaoit.chengquan.module.home.adapter.parts.MaintenanceAdapter;
import com.haitaoit.chengquan.module.home.model.MaintenanceModel;
import com.haitaoit.chengquan.module.home.model.TitleModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyGridView;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MaintenanceActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pull_refresh_scrollview)
    PullToRefreshScrollView pullrefreshscrollview;
    @ViewInject(R.id.select)
    TextView                select;

    private LinearLayout null_information_layout;
    private ScrollView   mScrollView;
    private MyListView   listView;


    private boolean isFrist = true;
    private int     page    = 1, type = 1, SelectIndex = 0;
    private MaintenanceAdapter adapter;
    private PopupWindow        myPopWindow;
    private String classification = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_maintenance);
        ViewUtils.inject(this);
        setLeftShow(1, R.mipmap.left);
        setTitle_V("系统维修");
        backLeft_V();


        View view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(true);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new MaintenanceAdapter(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MaintenanceActivity.this, MaintenanceDetailActivity2.class);
                intent.putExtra("id", adapter.getList().get(position).getId());
                startActivity(intent);
            }
        });
        httpGetmer_list();
    }

    @OnClick({R.id.maintenance_zonhe, R.id.maintenance_pingjia, R.id.maintenance_chengjiaol,
            R.id.select,})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.maintenance_zonhe:
                type = 1;
                isFrist = true;
                page = 1;
                httpGetmer_list();
                break;
            case R.id.maintenance_pingjia:
                type = 2;
                isFrist = true;
                page = 1;
                httpGetmer_list();
                break;
            case R.id.maintenance_chengjiaol:
                type = 3;
                isFrist = true;
                page = 1;
                httpGetmer_list();
                break;
            //筛选
            case R.id.select:
                iniPopupWindow();
                myPopWindow.showAsDropDown(select, 0, 0);
                break;
        }
        super.onClick(v);
    }

    // 弹出框
    private void iniPopupWindow() {
        // 服务分类0未选择2加工订单3机床耗材4机床配件5机床组立6二手设备买卖7二手设备改造
        List<TitleModel> titleList = new ArrayList<TitleModel>();
        titleList.add(new TitleModel("0", "全部"));
        titleList.add(new TitleModel("2", "加工订单"));
        titleList.add(new TitleModel("3", "机床耗材"));
        titleList.add(new TitleModel("4", "机床配件"));
        titleList.add(new TitleModel("5", "机床组立"));
        titleList.add(new TitleModel("6", "二手设备买卖"));
        titleList.add(new TitleModel("7", "设备改造"));

        View layout = LayoutInflater.from(this).inflate(R.layout.forum_down_item, null);
        layout.findViewById(R.id.forum_dismiss).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myPopWindow.dismiss();
            }
        });
        MyGridView forum_dwom_grid = (MyGridView) layout.findViewById(R.id.forum_dwom_grid);
        final ForumDownAdapter fdAdapter = new ForumDownAdapter(this);
        fdAdapter.setIsIndex(SelectIndex);
        fdAdapter.setList(titleList);
        fdAdapter.setBackCall(new BackCall() {
            @Override
            public void deal(int which, Object... obj) {
                int position = (Integer) obj[0];
                switch (which) {
                    case R.id.text:
                        SelectIndex = position;
                        classification = fdAdapter.getList().get(position).getId();
                        isFrist = true;
                        page = 1;
                        httpGetmer_list();
                        break;
                }
                myPopWindow.dismiss();
                super.deal(which, obj);
            }
        });

        if (titleList.size() >= 4) {
            forum_dwom_grid.setNumColumns(4);
            for (int i = 0; i < titleList.size(); i++) {
                if (titleList.get(i).getName().length() >= 6) {
                    forum_dwom_grid.setNumColumns(3);
                    break;
                }
            }
        }
        forum_dwom_grid.setAdapter(fdAdapter);

        myPopWindow = new PopupWindow(layout);
        myPopWindow.setFocusable(true); // 加上这个popupwindow中的ListView才可以接收点击事件
        // 控制popupwindow 的宽度和高度
        myPopWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        myPopWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);

        // 控制popupwindow 点击屏幕其他地方消失
        myPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.transparent)); // 设置背景图片,不能在布局中设置，要通过代码来设置
        myPopWindow.setOutsideTouchable(true);
        // 触摸popupwindow外部,popupwindow消失,这个要求你的popupwindow要有背景图片才可以成功
    }

    private void httpGetmer_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("type", type + ""));// 1综合2评价3成交量
        // 服务分类0未选择2加工订单3机床耗材4机床配件5机床组立6二手设备买卖7二手设备改造
        list.add(new NameValuePairSign("classification", classification));
        list.add(new NameValuePairSign("area", ""));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("type", type + "");
        params.addQueryStringParameter("classification", classification);
        params.addQueryStringParameter("area", "");
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        showProgrees("加载中，请稍等.....");
        HttpUtilsSingle.doGet(this, false, Constant.Getmer_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<MaintenanceModel> new_list = new ArrayList<MaintenanceModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<MaintenanceModel>();
                            hideProgree();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<MaintenanceModel>>() {
                                    }.getType());
                            hideProgree();
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<MaintenanceModel>();
                            hideProgree();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<MaintenanceModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                    hideProgree();
                } catch (JSONException e) {
                    e.printStackTrace();
                    hideProgree();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
                hideProgree();
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<MaintenanceModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        httpGetmer_list();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        httpGetmer_list();
    }

}
